package com.fast.mybatis;

import com.fast.mybatis.freemarkerConfig.Attribute;
import com.fast.mybatis.freemarkerConfig.FreeMarkerConfig;
import com.fast.mybatis.util.*;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.io.*;
import java.util.*;

/**
 * @Author likaixuan
 * @Description
 * @Create Date  2018/9/4 22:24
 * @Version 1.0
 */
public class TemplateUtil {

    //生成bean
    public static void getBean(List<TableFiledEntity> list, String beanPath, String tableName, String author, String rootPath) throws Exception {

        OutputStream fos = null;
        try {
            //获取模板
            Template temp = FreeMarkerConfig.getInstance().getDefinedTemplate("javabean.ftl");
            //设置根值
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("packageName", beanPath);
            root.put("className", tableName);
            root.put("author", author);
            root.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            List<Attribute> attr_list = new ArrayList<Attribute>();
            List<Attribute> attrTypeList = new ArrayList<>();
            for (TableFiledEntity table : list) {
                attr_list.add(new Attribute(table.getFiledMark(), table.getFiledType(), StringUtil.processColnames(table.getFiledName()), StringUtil.toUpperCaseFirstOne(StringUtil.processColnames(table.getFiledName()))));
                String importType = MySqlDBUtil.JavaBeanDataType(table.getFiledType());
                if (!StringUtils.isEmpty(importType)) {
                    if (attrTypeList.size() == 0) {
                        attrTypeList.add(new Attribute(importType));
                    }
                    boolean boo = false;
                    for (int i = 0; i < attrTypeList.size(); i++) {
                        if (attrTypeList.get(i).getImportType().equals(importType)) {
                            boo = true;
                            break;
                        }
                    }
                    if (!boo) {
                        attrTypeList.add(new Attribute(importType));
                    }
                }
            }
            root.put("attrs", attr_list);
            root.put("attrTypeList", attrTypeList);
            String temPath = beanPath.replaceAll("\\.", "\\\\");

            String path = rootPath + temPath + "\\";
            isexitsPath(path);
            fos = new FileOutputStream(new File(path, tableName + ".java"));
            Writer out = new OutputStreamWriter(fos);
            temp.process(root, out);
        } catch (Exception ex) {

        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }

    }

    //生成Dao
    public static void getBaseDao(String DaoPath, String tableName, String author, String rootPath) throws Exception {
        OutputStream fos = null;
        try {
            //获取模板
            Template temp = FreeMarkerConfig.getInstance().getDefinedTemplate("BaseMapper.ftl");
            //设置根值
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("packageName", DaoPath);
            root.put("className", tableName);
            root.put("author", author);
            root.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));

            String temPath = DaoPath.replaceAll("\\.", "\\\\");

            String path = rootPath + temPath + "\\";
            isexitsPath(path);
            fos = new FileOutputStream(new File(path, "BaseMapper.java"));
            Writer out = new OutputStreamWriter(fos);
            temp.process(root, out);

        } catch (Exception ex) {

        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }
    }

    //生成Dao
    public static void getDao(List<TableFiledEntity> list, String DaoPath, String tableName, String entityPath, String author, String rootPath) throws Exception {
        OutputStream fos = null;
        try {
            //获取模板
            Template temp = FreeMarkerConfig.getInstance().getDefinedTemplate("Dao.ftl");
            //设置根值
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("packageName", DaoPath);
            root.put("className", tableName);
            root.put("entityPath", entityPath);
            root.put("author", author);
            root.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            List<Attribute> attr_list = new ArrayList<Attribute>();
            for (TableFiledEntity table : list) {
                attr_list.add(new Attribute(table.getFiledMark(), table.getFiledType(), StringUtil.processColnames(table.getFiledName()), StringUtil.toUpperCaseFirstOne(StringUtil.processColnames(table.getFiledName()))));
            }
            root.put("attrs", attr_list);

            String temPath = DaoPath.replaceAll("\\.", "\\\\");

            String path = rootPath + temPath + "\\";
            isexitsPath(path);
            fos = new FileOutputStream(new File(path, tableName + "Mapper.java"));
            Writer out = new OutputStreamWriter(fos);
            temp.process(root, out);
        } catch (Exception ex) {

        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }
    }

    //生成XML
    public static void getMapper(List<TableFiledEntity> list, String DaoPath, String mapperPath, String entityPath, String tableName, String author, String rootPath) throws Exception {
        OutputStream fos = null;
        try {
            //获取模板
            Template temp = FreeMarkerConfig.getInstance().getDefinedTemplate("Mapper.ftl");
            //设置根值
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("packageName", DaoPath);
            root.put("tableName", tableName);
            root.put("className", StringUtil.toUpperCaseFirstOne(tableName));
            root.put("entityPath", entityPath);
            root.put("author", author);
            root.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            List<Attribute> attr_list = new ArrayList<Attribute>();

            int count = 0;
            for (TableFiledEntity table : list) {
                attr_list.add(new Attribute(table.getFiledName(), table.getDbFiledName()));
                //如果是主键,如果表没有主键，就用第一个字段
                boolean flag = false;
                if (table.getKey()) {
                    flag = true;
                    root.put("key", table.getDbFiledName());
                    root.put("val", table.getFiledName());
                }
                count++;
                if (count == list.size() && !flag) {
                    root.put("key", list.get(0).getDbFiledName());
                    root.put("val", list.get(0).getFiledName());
                }
            }
            root.put("attrs", attr_list);

            String temPath = mapperPath.replaceAll("\\.", "\\\\");

            String path = rootPath + temPath + "\\";
            isexitsPath(path);
            fos = new FileOutputStream(new File(path, StringUtil.toUpperCaseFirstOne(tableName) + "Mapper.xml"));
            Writer out = new OutputStreamWriter(fos);
            temp.process(root, out);
        } catch (Exception ex) {

        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }
    }

    //生成Service
    public static void getService(List<TableFiledEntity> list, String servicePath, String entityPath, String tableName, String author, String rootPath) throws Exception {
        OutputStream fos = null;
        try {
            //获取模板
            Template temp = FreeMarkerConfig.getInstance().getDefinedTemplate("Service.ftl");
            //设置根值
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("packageName", servicePath);
            root.put("className", tableName);
            root.put("entityPath", entityPath);
            root.put("author", author);
            root.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            List<Attribute> attr_list = new ArrayList<Attribute>();
            for (TableFiledEntity table : list) {
                attr_list.add(new Attribute(table.getFiledMark(), table.getFiledType(), StringUtil.processColnames(table.getFiledName()), StringUtil.toUpperCaseFirstOne(StringUtil.processColnames(table.getFiledName()))));
            }
            root.put("attrs", attr_list);

            String temPath = servicePath.replaceAll("\\.", "\\\\");

            String path = rootPath + temPath + "\\";
            isexitsPath(path);
            fos = new FileOutputStream(new File(path, tableName + "Service.java"));
            Writer out = new OutputStreamWriter(fos);
            temp.process(root, out);
        } catch (Exception ex) {

        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }

    }

    //生成ServiceImpl
    public static void getServiceImpl(List<TableFiledEntity> list, String servicePath, String entityPath, String daoPath, String tableName, String lowTableName, String author, String rootPath) throws Exception {
        OutputStream fos = null;
        try {
            //获取模板
            Template temp = FreeMarkerConfig.getInstance().getDefinedTemplate("ServiceImpl.ftl");
            //设置根值
            Map<String, Object> root = new HashMap<String, Object>();
            root.put("packageName", servicePath + ".impl");
            root.put("className", tableName);
            root.put("lowClassName", lowTableName);
            root.put("entityPath", entityPath);
            root.put("daoPath", daoPath);
            root.put("servicePath", servicePath);
            root.put("author", author);
            root.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            List<Attribute> attr_list = new ArrayList<Attribute>();
            for (TableFiledEntity table : list) {
                attr_list.add(new Attribute(table.getFiledMark(), table.getFiledType(), StringUtil.processColnames(table.getFiledName()), StringUtil.toUpperCaseFirstOne(StringUtil.processColnames(table.getFiledName()))));
            }
            root.put("attrs", attr_list);

            String temPath = servicePath.replaceAll("\\.", "\\\\");

            String path = rootPath + temPath + "\\";
            isexitsPath(path);
            fos = new FileOutputStream(new File(path, tableName + "ServiceImpl.java"));
            Writer out = new OutputStreamWriter(fos);
            temp.process(root, out);
        } catch (Exception ex) {

        } finally {
            if (null != fos) {
                fos.flush();
                fos.close();
            }
        }


    }


    /**
     * 是否创建目录
     *
     * @param path
     * @return
     */
    public static boolean isexitsPath(String path) throws InterruptedException {
        String[] paths = path.split("\\\\");
        StringBuffer fullPath = new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file = new File(fullPath.toString());
            if (paths.length != i) {
                if (!file.exists()) {
                    file.mkdir();
                }
            }
        }
        File file = new File(fullPath.toString());
        if (!file.exists()) {
            return true;
        } else {
            return false;
        }
    }


}
